import axios from 'axios';
import http from 'http'; // 引入 Node.js 的 http 模块

// 创建自定义 Agent 绑定到 5173 端口
const customAgent = new http.Agent({
    localPort: 5173,  // 客户端绑定到此端口
    family: 4,        // 强制使用 IPv4
    keepAlive: true   // 保持连接
});

// 创建 Axios 实例 - 目标服务器端口为 8080
const api = axios.create({
    baseURL: 'http://localhost:8080',
    withCredentials: true, // 允许携带 cookie
    httpAgent: customAgent, // 使用自定义 Agent
    timeout: 5000
});

// 登录请求
const login = async () => {
    try {
        const response = await api.post('/user/login', {
            email: "root1@example.com",
            password: "123456"
        });

        console.log('登录成功:', {
            status: response.status,
            data: response.data
        });
        return response;
    } catch (error) {
        console.error('登录失败:', {
            message: error.message,
            code: error.code,
            response: error.response?.data
        });
        throw error;
    }
};

// 登录状态检查
const checkLoginStatus = async () => {
    try {
        const response = await api.get('/user/check-login');
        console.log('登录状态:', {
            status: response.status,
            data: response
        });
        return response;
    } catch (error) {
        console.error('状态检查失败:', {
            message: error.message,
            code: error.code,
            response: error.response?.data
        });
        throw error;
    }
};

// 主执行流程
const main = async () => {
    try {
        console.log('从 5173 端口向 8080 端口发送请求...');
        await login();
        await checkLoginStatus();
        console.log('测试完成');
    } catch (error) {
        console.error('测试失败:', error);
    } finally {
        // 确保关闭连接
        customAgent.destroy();
    }
};

main();